package model.textchatserver;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PushbackInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

import model.roomManagement.Implementation.Server;


public class RoomTChatSocketsManager implements Runnable
{
	private ArrayList< Socket > sources = new ArrayList<Socket>();
	private int roomId;
	private boolean conti = true;

	private RoomMessageHandler rmHandler;

	
	public RoomTChatSocketsManager(int roomId)
	{
		this.roomId = roomId;
		rmHandler = new RoomMessageHandler();
		Thread rmhThread = new Thread( rmHandler );
		rmhThread.start();
		
		Thread rtcsmThread = new Thread( this );
		rtcsmThread.start();
	}
	
	public synchronized void addNewSocket( Socket socket )
	{
		
		sources.add( socket );
		update();
	}
	

	private synchronized void update()
	{

		rmHandler.updateSocketsInfo( sources );
	}
	
	public void end()
	{
		rmHandler.end();
		Server.deleteRoom( roomId );
		conti = false;
	}

	@Override
	public void run()
	{
		
		while ( conti )
		{
			checkSocketStatus();
			try 
			{
				Thread.sleep( 100 );
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	
	}
	
	private synchronized void checkSocketStatus() 
	{
		boolean changed = false;
		Iterator<Socket> iterator = sources.iterator();
		while ( iterator.hasNext() )
		{
			Socket socket = iterator.next();
			if ( socket.isClosed() )
			{
		
				iterator.remove();
				changed = true;
			}
		}
		
		if( changed )
		{
			update();
		}
		
		if ( sources.size() == 0 )
		{
			end();
		}
		
	}
}
